from django.shortcuts import render
from django.views import View
import logging
from django import http
from django.core.cache import cache

from meiduo_mall.utils.response_code import RETCODE
from areas.models import Area
# Create your views here.


logger = logging.getLogger('django')


class AreasView(View):
    """省市区三级联动"""
    def get(self, request):
        """判断当前需要查询的是省级数据还是市级数据"""
        area_id = request.GET.get('area_id')

        if not area_id:
            # 判断是佛有缓存数据
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    # 提供省份数据
                    province_model_list = Area.objects.filter(parent__isnull=True) # 两个下划线

                    # JsonResponse只能响应字典，列表，字典列表，所以要讲province_model_list转换成字典列表
                    province_list = []
                    for province_model in province_model_list:
                        province_dict={
                            'id':province_model.id,
                            'name':province_model.name,
                        }
                        province_list.append(province_dict)

                    # 缓存省份字典列表数据:默认存储到别名为"default"的配置中
                    cache.set( 'province_list', province_list, 3600 )
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code':RETCODE.DBERR,'errmsg': '省份数据错误'})

                # 响应省级JSON数据
            return http.JsonResponse( {'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list} )

        else:
            # 判断是否有缓存
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:
                    # 查询市级或者县级数据
                    parent_model = Area.objects.get(id=area_id)
                    # sub_model_list=parent_model.area_set.all()
                    sub_model_list = parent_model.subs.all()

                    # 将子模型类转换成列表字典
                    subs = []
                    for sub_model in sub_model_list:
                        sub_dict = {
                            'id': sub_model.id,
                            'name': sub_model.name,
                        }
                        subs.append(sub_dict)
                        # 构造子级JSON数据
                    sub_data = {
                        'id':parent_model.id,
                        'name':parent_model.name,
                        'subs':subs
                    }
                    # 缓存城市或者区县
                    cache.set('sub_area_' + area_id, sub_data, 3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code':RETCODE.DBERR, 'errmsg':'查询城市或者县市似乎局错误'})
            # 响应json数据
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})





